{% extends 'members/base.html' %}
{% set active_page = 'records' %}

{% block title %}我的记录{% endblock %}

{% block extra_css %}
<style>
/* 测评记录页面专用样式 */
.records-container {
    padding: 1rem;
}

/* 筛选区域 */
.filter-section {
    background: white;
    border-radius: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
    padding: 2rem;
    margin-bottom: 2rem;
    border: 1px solid #f1f3f4;
}

.scale-select {
    min-width: 300px;
}

/* 记录卡片 */
.record-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    border: 1px solid #f1f3f4;
    margin-bottom: 1rem;
    transition: all 0.3s ease;
    cursor: pointer;
}

.record-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0,0,0,0.1);
    border-color: #667eea;
}

.record-card.risk-low {
    border-left: 4px solid #28a745;
}

.record-card.risk-medium {
    border-left: 4px solid #ffc107;
}

.record-card.risk-high {
    border-left: 4px solid #dc3545;
}

.record-header {
    padding: 1.5rem 1.5rem 0.5rem;
    border-bottom: 1px solid #f8f9fa;
}

.record-body {
    padding: 1rem 1.5rem;
}

.record-footer {
    padding: 0.5rem 1.5rem 1.5rem;
    background: #f8f9fa;
    border-radius: 0 0 12px 12px;
}

/* 状态徽章 */
.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
}

.status-completed {
    background: #d4edda;
    color: #155724;
}

.status-in-progress {
    background: #fff3cd;
    color: #856404;
}

.status-not-started {
    background: #f8d7da;
    color: #721c24;
}

/* 风险徽章 */
.risk-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
}

.risk-badge.risk-low {
    background: #d4edda;
    color: #155724;
}

.risk-badge.risk-medium {
    background: #fff3cd;
    color: #856404;
}

.risk-badge.risk-high {
    background: #f8d7da;
    color: #721c24;
}

/* 分数显示 */
.score-display {
    font-size: 2rem;
    font-weight: bold;
    color: #2c3e50;
}

/* 进度条 */
.progress-custom {
    height: 8px;
    border-radius: 4px;
}

/* 空状态 */
.empty-state {
    text-align: center;
    padding: 4rem 2rem;
    color: #6c757d;
}

.empty-state i {
    font-size: 4rem;
    opacity: 0.3;
    margin-bottom: 1rem;
}

/* 加载状态 */
.loading-state {
    text-align: center;
    padding: 3rem;
    color: #6c757d;
}

.loading-spinner {
    width: 3rem;
    height: 3rem;
    margin: 0 auto 1rem;
}

/* 统计信息 */
.stats-row {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 2rem;
}

.stat-item {
    text-align: center;
}

.stat-number {
    font-size: 2rem;
    font-weight: bold;
    margin-bottom: 0.5rem;
}

.stat-label {
    font-size: 0.9rem;
    opacity: 0.9;
}
</style>
{% endblock %}

{% block content %}
<div class="records-container">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="mb-1">我的记录</h2>
            <p class="text-muted mb-0">查看和管理您的测评记录</p>
        </div>
        <div>
            <button class="btn btn-outline-primary me-2" onclick="exportRecords()">
                <i class="bi bi-download me-1"></i>导出记录
            </button>
            <button class="btn btn-primary" onclick="window.location.href='/members/scale-library'">
                <i class="bi bi-plus-circle me-1"></i>开始测评
            </button>
        </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
        <div class="row align-items-center">
            <div class="col-md-6">
                <label class="form-label">选择量表:</label>
                <select class="form-select scale-select" id="scale-select" onchange="loadRecords()">
                    <option value="">请选择量表...</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">状态筛选:</label>
                <select class="form-select" id="status-filter" onchange="filterRecords()">
                    <option value="">全部状态</option>
                    <option value="completed">已完成</option>
                    <option value="in_progress">进行中</option>
                    <option value="not_started">未开始</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">排序方式:</label>
                <select class="form-select" id="sort-select" onchange="sortRecords()">
                    <option value="created_at_desc">创建时间(新到旧)</option>
                    <option value="created_at_asc">创建时间(旧到新)</option>
                    <option value="score_desc">分数(高到低)</option>
                    <option value="score_asc">分数(低到高)</option>
                    <option value="status">状态</option>
                </select>
            </div>
        </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-row" id="stats-section" style="display: none;">
        <div class="row">
            <div class="col-md-3 stat-item">
                <div class="stat-number" id="total-count">0</div>
                <div class="stat-label">总测评次数</div>
            </div>
            <div class="col-md-3 stat-item">
                <div class="stat-number" id="completed-count">0</div>
                <div class="stat-label">完成次数</div>
            </div>
            <div class="col-md-3 stat-item">
                <div class="stat-number" id="average-score">-</div>
                <div class="stat-label">平均分数</div>
            </div>
            <div class="col-md-3 stat-item">
                <div class="stat-number" id="last-assessment">-</div>
                <div class="stat-label">最近测评</div>
            </div>
        </div>
    </div>

    <!-- 加载状态 -->
    <div class="loading-state" id="loading-state" style="display: none;">
        <div class="spinner-border loading-spinner" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p>正在加载测评记录...</p>
    </div>

    <!-- 记录列表 -->
    <div id="records-container">
        <!-- 记录将在这里动态生成 -->
    </div>

    <!-- 空状态 -->
    <div class="empty-state" id="empty-state" style="display: none;">
        <i class="bi bi-clipboard-data"></i>
        <h5>暂无测评记录</h5>
        <p>请先选择量表查看对应的测评记录</p>
    </div>

    <!-- 分页 -->
    <nav aria-label="记录分页" id="pagination-container" style="display: none;">
        <ul class="pagination justify-content-center" id="pagination">
            <!-- 分页将在这里动态生成 -->
        </ul>
    </nav>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 全局变量
let allScales = [];
let allRecords = [];
let filteredRecords = [];
let currentScaleId = null;
let currentPage = 1;
let totalPages = 1;

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面初始化开始');
    loadScales();
});

// 加载量表列表
async function loadScales() {
    try {
        console.log('开始加载量表列表');
        const data = await apiRequest('/api/scales/my');
        
        if (data.success) {
            allScales = data.data.scales || [];
            console.log('加载到的量表数量:', allScales.length);
            renderScaleSelect();
        } else {
            console.error('加载量表失败:', data.message);
            showError('加载量表失败: ' + data.message);
        }
    } catch (error) {
        console.error('加载量表出错:', error);
        showError('网络错误，请稍后重试');
    }
}

// 渲染量表下拉选择器
function renderScaleSelect() {
    const select = document.getElementById('scale-select');
    let html = '<option value="">请选择量表...</option>';
    
    allScales.forEach(scale => {
        html += `<option value="${scale.id}">${scale.title}</option>`;
    });
    
    select.innerHTML = html;
    console.log('量表选择器渲染完成');
}

// 加载测评记录
async function loadRecords() {
    const scaleId = document.getElementById('scale-select').value;
    
    if (!scaleId) {
        // 清空记录显示
        document.getElementById('records-container').innerHTML = '';
        document.getElementById('stats-section').style.display = 'none';
        document.getElementById('empty-state').style.display = 'block';
        document.getElementById('pagination-container').style.display = 'none';
        return;
    }
    
    currentScaleId = scaleId;
    showLoading(true);
    
    try {
        console.log('开始加载测评记录, scaleId:', scaleId);
        const data = await apiRequest(`/api/scales/${scaleId}/assessments`);
        
        console.log('API响应:', data);
        
        if (data.success) {
            allRecords = data.data.assessments || [];
            console.log('加载到的记录数量:', allRecords.length);
            
            // 显示统计信息
            displayStats(data.data.stats);
            
            // 应用筛选和排序
            filterRecords();
        } else {
            console.error('加载记录失败:', data.message);
            showError('加载记录失败: ' + data.message);
            showEmptyState();
        }
    } catch (error) {
        console.error('加载记录出错:', error);
        showError('网络错误，请稍后重试');
        showEmptyState();
    } finally {
        showLoading(false);
    }
}

// 显示统计信息
function displayStats(stats) {
    if (!stats) return;
    
    document.getElementById('total-count').textContent = stats.total_count || 0;
    document.getElementById('completed-count').textContent = stats.completed_count || 0;
    document.getElementById('average-score').textContent = stats.average_score ? stats.average_score.toFixed(1) : '-';
    document.getElementById('last-assessment').textContent = stats.last_assessment_date ? formatDate(stats.last_assessment_date) : '-';
    
    document.getElementById('stats-section').style.display = 'block';
}

// 筛选记录
function filterRecords() {
    const statusFilter = document.getElementById('status-filter').value;
    
    if (statusFilter) {
        filteredRecords = allRecords.filter(record => record.status === statusFilter);
    } else {
        filteredRecords = [...allRecords];
    }
    
    console.log('筛选后的记录数量:', filteredRecords.length);
    sortRecords();
}

// 排序记录
function sortRecords() {
    const sortBy = document.getElementById('sort-select').value;
    
    switch (sortBy) {
        case 'created_at_desc':
            filteredRecords.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
            break;
        case 'created_at_asc':
            filteredRecords.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
            break;
        case 'score_desc':
            filteredRecords.sort((a, b) => (b.total_score || 0) - (a.total_score || 0));
            break;
        case 'score_asc':
            filteredRecords.sort((a, b) => (a.total_score || 0) - (b.total_score || 0));
            break;
        case 'status':
            filteredRecords.sort((a, b) => a.status.localeCompare(b.status));
            break;
    }
    
    renderRecords();
}

// 渲染记录列表
function renderRecords() {
    const container = document.getElementById('records-container');
    const emptyState = document.getElementById('empty-state');
    
    if (filteredRecords.length === 0) {
        container.innerHTML = '';
        emptyState.style.display = 'block';
        document.getElementById('pagination-container').style.display = 'none';
        return;
    }
    
    emptyState.style.display = 'none';
    
    let html = '';
    filteredRecords.forEach(record => {
        html += generateRecordCard(record);
    });
    
    container.innerHTML = html;
    console.log('记录渲染完成，生成HTML长度:', html.length);
}

// 生成单个记录卡片
function generateRecordCard(record) {
    const statusText = getStatusText(record.status);
    const statusClass = getStatusClass(record.status);
    const riskLevel = getRiskLevel(record.total_score);
    const riskText = getRiskText(riskLevel);
    const progress = getProgress(record);
    const duration = getDuration(record);
    
    return `
        <div class="record-card risk-${riskLevel}" onclick="viewRecordDetail(${record.id})">
            <div class="record-header">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h6 class="mb-1">测评记录 #${record.id}</h6>
                        <small class="text-muted">创建时间: ${formatDateTime(record.created_at)}</small>
                        <br>
                        <small class="text-info">用户: ${record.user_name || '匿名用户'}</small>
                    </div>
                    <div class="col-md-4 text-end">
                        <span class="status-badge ${statusClass}">${statusText}</span>
                        <br>
                        <span class="risk-badge risk-${riskLevel} mt-1">${riskText}</span>
                    </div>
                </div>
            </div>
            <div class="record-body">
                <div class="row align-items-center">
                    <div class="col-md-2 text-center">
                        <div class="score-display">${record.total_score || '--'}</div>
                        <small class="text-muted">总分</small>
                    </div>
                    <div class="col-md-10">
                        <div class="row">
                            <div class="col-md-4">
                                <strong>完成进度:</strong>
                                <div class="progress progress-custom mt-1">
                                    <div class="progress-bar bg-primary" style="width: ${progress}%"></div>
                                </div>
                                <small class="text-muted">${progress}%</small>
                            </div>
                            <div class="col-md-4">
                                <strong>用时:</strong><br>
                                <span>${duration}</span>
                            </div>
                            <div class="col-md-4">
                                <strong>完成时间:</strong><br>
                                <span>${record.completed_at ? formatDateTime(record.completed_at) : '未完成'}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="record-footer">
                <div class="d-flex justify-content-between align-items-center">
                    <small class="text-muted">点击查看详细报告</small>
                    <div>
                        ${record.status === 'completed' ? `
                        <button class="btn btn-sm btn-success" onclick="event.stopPropagation(); downloadReport(${record.id})">
                            <i class="bi bi-download me-1"></i>下载报告
                        </button>
                        ` : ''}
                        ${record.status === 'in_progress' ? `
                        <button class="btn btn-sm btn-warning" onclick="event.stopPropagation(); continueAssessment(${record.id})">
                            <i class="bi bi-play me-1"></i>继续测评
                        </button>
                        ` : ''}
                    </div>
                </div>
            </div>
        </div>
    `;
}

// 查看记录详情
function viewRecordDetail(recordId) {
    console.log('查看记录详情, recordId:', recordId);
    window.open(`/assessments/${recordId}/results`, '_blank');
}

// 下载报告
function downloadReport(recordId) {
    console.log('下载报告, recordId:', recordId);
    window.open(`/api/assessments/${recordId}/report`, '_blank');
}

// 继续测评
function continueAssessment(recordId) {
    console.log('继续测评, recordId:', recordId);
    window.location.href = `/assessments/${recordId}/continue`;
}

// 导出记录
function exportRecords() {
    if (!currentScaleId) {
        alert('请先选择量表');
        return;
    }
    window.open(`/api/scales/${currentScaleId}/assessments/export`, '_blank');
}

// 工具函数
function getStatusText(status) {
    const statusMap = {
        'completed': '已完成',
        'in_progress': '进行中',
        'not_started': '未开始'
    };
    return statusMap[status] || status;
}

function getStatusClass(status) {
    const classMap = {
        'completed': 'status-completed',
        'in_progress': 'status-in-progress',
        'not_started': 'status-not-started'
    };
    return classMap[status] || 'status-not-started';
}

function getRiskLevel(score) {
    if (!score) return 'low';
    if (score >= 70) return 'high';
    if (score >= 40) return 'medium';
    return 'low';
}

function getRiskText(riskLevel) {
    const riskMap = {
        'low': '低风险',
        'medium': '中风险',
        'high': '高风险'
    };
    return riskMap[riskLevel] || riskLevel;
}

function getProgress(record) {
    if (record.status === 'completed') return 100;
    if (record.status === 'not_started') return 0;
    return record.progress || 0;
}

function getDuration(record) {
    if (record.duration) {
        const minutes = Math.floor(record.duration / 60);
        const seconds = record.duration % 60;
        return `${minutes}分${seconds}秒`;
    }
    return '未知';
}

function formatDate(dateString) {
    if (!dateString) return '未知';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

function formatDateTime(dateString) {
    if (!dateString) return '未知';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

// 显示/隐藏加载状态
function showLoading(show) {
    const loadingState = document.getElementById('loading-state');
    const recordsContainer = document.getElementById('records-container');
    const emptyState = document.getElementById('empty-state');
    
    if (show) {
        loadingState.style.display = 'block';
        recordsContainer.innerHTML = '';
        emptyState.style.display = 'none';
    } else {
        loadingState.style.display = 'none';
    }
}

// 显示空状态
function showEmptyState() {
    document.getElementById('records-container').innerHTML = '';
    document.getElementById('empty-state').style.display = 'block';
    document.getElementById('stats-section').style.display = 'none';
    document.getElementById('pagination-container').style.display = 'none';
}

// 显示错误信息
function showError(message) {
    alert('错误: ' + message);
}

// 注意：apiRequest函数已在base.html中定义，包含了认证逻辑
</script>
{% endblock %}